define([
	"static/app/tips",
	"UtilDir/util",
	"UtilDir/tool",
    "UtilDir/org/selectOrg",
    "UtilDir/searchBlock",
	"UtilDir/loading",
	"http://api.tianditu.gov.cn/api?v=4.0&tk=aeb17a8215786a5dd17f5f9c92bebc0c",
	"Date","DateCN", "css!DateCss",
	"EasyUI","EasyUI-lang"
    ],function(tips, Util, Tool, SelectOrg, SearchBlock, Loading){

    var sysPath =  getServer() + "/static/app/zdyh/yhdisasterhiddenLevel";

	var getBoundaryController = function(){
		return getServer() + "/boundary";
	};
	var getDistrictDataController = function(){
		return getServer() + "/yh/yhDisasters";
	};

	/**
	 * 页面初始化
	 */
	var init = function(){
		var t = setInterval(function () {
			if (T.PolygonTool) {
				clearInterval(t);
				initcreateProvince();
				initMap();
				initSearchBlock();
				queryBtnBind();
			}
		}, 10);
	};

	var initcreateProvince = function () {
		var html = "";
		$("#provinceSelect").append('<option value="" >请选择</option>');
		$("#citySelect").append(html);
		$("#areaSelect").append(html);
		$.ajax({
			url: getServer() + "/divisions/root/subdivisions",
			contentType: "application/json",
			type: "get",
			success: function (data) {
				$.each(data, function (idx, item) {
					html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
				});
				$("#provinceSelect").append(html);
			}
		});
		$("#provinceSelect").change(function () {
			var html = '<option value="" disabled selected style="display:none;">请选择</option>';
			$("#citySelect option").remove();
			$("#citySelect").append(html);
			$("#areaSelect option").remove();
			$("#areaSelect").append(html);
			var divisionId = $(this).find("option:selected").attr("exid");
			if ($(this).val() == "北京市" || $(this).val() == "天津市" || $(this).val() == "上海市" || $(this).val() == "重庆市") {
				$("#citySelect").append('<option value="" >请选择</option>');
				$("#citySelect").append("<option value='" + $(this).val() + "' exid='" + divisionId + "'>" + $(this).val() + "</option>");
				changeDistrictType();
				return;
			}
			changeDistrictType();
			$("#citySelect").append('<option value="" >请选择</option>');
			$.ajax({
				url: getServer() + "/divisions/" + divisionId + "/subdivisions",
				contentType: "application/json",
				type: "get",
				success: function (data) {
					$.each(data, function (idx, item) {
						html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
					});
					$("#citySelect").append(html);
				}
			});
		});
		$("#citySelect").change(function () {
			if ($(this).val() == "") return;
			var html = '<option value="" disabled selected style="display:none;">请选择</option>';
			$("#areaSelect option").remove();
			$("#areaSelect").append(html);
			changeDistrictType();
			$("#areaSelect").append('<option value="" >请选择</option>');
			var divisionId = $(this).find("option:selected").attr("exid");
			$.ajax({
				url: getServer() + "/divisions/" + divisionId + "/subdivisions",
				contentType: "application/json",
				type: "get",
				success: function (data) {
					$.each(data, function (idx, item) {
						html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
					});
					$("#areaSelect").append(html);
				}
			});
		});
		$("#areaSelect").change(function () {
			changeDistrictType();
		});
	};

	var initSearchBlock = function(){
        SearchBlock.init("searchBlock");
	};
	var queryBtnBind = function(){
		$("#operatePanelButton").click(function () {
			var operatePanel = $("#operatePanel");
			if (operatePanel.is(":visible")) {
				operatePanel.css("display", "none");
				$(this).children().eq(0).css("background-position", "0 0");
			} else {
				$(this).children().eq(0).css("background-position", "0 46px");
				operatePanel.css("display", "block");
				clearPolygons();
			}
		});

		$("#button-closeForm").click(function () {
			$("#operatePanel").css("display", "none");
			$("#operatePanelButton").children().eq(0).css("background-position", "0 0");
		});

		$("#btnSearch").click(function () {
			queryDistrictData();
		});
		$("#btnDistrictSearch").click(function () {
			polygonTool.open();
		});
		$("#qh_district_div input[type=radio][value='p']").click(function () {
			var province = $("#provinceSelect").val() || "", city = $("#citySelect").val() || "", area = $("#areaSelect").val() || "";
			if (province == "" && city == "" && area == "") {
				$("#qh_district_div input[type=radio][value='p']").prop("checked",'checked');
				$("#qh_district_div input[type=radio][value='c']").prop("disabled",true);
				$("#qh_district_div input[type=radio][value='a']").prop("disabled",true);
			}
		});

		polygonTool.addEventListener("draw", function (obj) {
			console.log(obj);
			tdMap.removeOverLay(obj.currentPolygon);
			var coords_str = "";
			var lnglats = obj.currentLnglats, lnglat, xD = [], yD = [];
			for (let i = 0; i < lnglats.length; i++) {
				lnglat = lnglats[i];
				xD.push(lnglat.lat);
				yD.push(lnglat.lng);
				coords_str += (lnglat.lat + "," + lnglat.lng + ";");
			}
			coords_str = coords_str.substring(0, coords_str.length - 1);
			console.log(coords_str);
			var coords = {xD: xD, yD: yD};
			queryProvincesByCoords(coords_str, coords);

			//queryDistrictData(coords);
			polygonTool.close();
		});

	};

	var changeDistrictType = function () {
		$("#qh_district_div input[type=radio]").attr("disabled",false).prop("checked",'');
		var province = $("#provinceSelect").val() || "", city = $("#citySelect").val() || "", area = $("#areaSelect").val() || "";
		console.log("province: ", province, "city: ", city, "area: ", area);
		if (province != "") {
			$("#qh_district_div input[type=radio][value='p']").prop("checked",'checked');
			$("#qh_district_div input[type=radio][value='c']").prop("checked",'');
			$("#qh_district_div input[type=radio][value='a']").prop("checked",'');
		} else {
			$("#qh_district_div input[type=radio][value='p']").prop("checked",'checked');
			$("#qh_district_div input[type=radio][value='c']").prop("disabled",true);
			$("#qh_district_div input[type=radio][value='a']").prop("disabled",true);
		}
		if (province != "" && city != "") {
			$("#qh_district_div input[type=radio][value='p']").attr("disabled",true);
			$("#qh_district_div input[type=radio][value='c']").prop("checked",'checked');
			$("#qh_district_div input[type=radio][value='a']").prop("checked",'');
		}
		if (province != "" && city != "" && area != "") {
			$("#qh_district_div input[type=radio][value='p']").attr("disabled",true);
			$("#qh_district_div input[type=radio][value='c']").attr("disabled",true);
			$("#qh_district_div input[type=radio][value='a']").prop("checked",'checked');
		}
	};
	var queryDistrictData = function (coords, _province) {
		var province = _province || $("#provinceSelect").val() || "", city = $("#citySelect").val() || "", area = $("#areaSelect").val() || "";
		var district_level = $("#qh_district_div input[type=radio]:checked").val(),
			building_type = $("#qh_building_type_div input[type=radio]:checked").val(),
			qh_sign = $("#qh_sign_div input[type=radio]:checked").val();
		console.log(province, city, area, district_level, building_type);
		_queryDistrictResult(province, city, area, district_level, building_type, qh_sign, coords);
	};
	var _queryDistrictResult = function (province, city, area, level, bearDisasterBodyType, sign, coords) {
		var param_obj = {province: province, city: city, area: area, level: level, bearDisasterBodyType: bearDisasterBodyType, sign: sign};
		coords && (param_obj.xD = coords.xD, param_obj.yD = coords.yD);
		!coords && loading.show(); tdMap.closeInfoWindow();
		$.ajax({
			url: getDistrictDataController() + "/rpheq?",
			type: "POST",
			contentType: "application/json; charset=utf-8",
			data: JSON.stringify(param_obj),
			success: function (data) {
				console.log(data);
				if (typeof(data) == "string") {
					loading.close();
					if (!coords) Util.alert(data);
				} else {
					var _data = swapObj(data);
					(_data.length) ? (city = _data[0], data = _data[1]) : (data = _data);
					console.log(province, city, area, level, data);
					renderDistrictBoundary(province, city, area, level, data);
				}
			}
		});
	};
	var renderDistrictBoundary = function (province, city, area, level, data) {
		if (province != "" && city == "" && area == "" || province == "" && city == "" && area == "") {
			if (level == "p") {
				for (const province_name in data) {
					global_taskIsFinished[province_name] = false;
					querySingleProvinceBoundary(province_name, rank_color[data[province_name]], data);
				}
			} else if (level == "c") {
				for (const city_name in data) {
					global_taskIsFinished[city_name] = false;
					querySingleCityBoundary(province, city_name, rank_color[data[city_name]]);
				}
			} else if (level == "a") {
				for (const area_name in data) {
					global_taskIsFinished[area_name] = false;
					querySingleAreaBoundary(province, city, area_name, rank_color[data[area_name]]);
				}
			}
		} else if (province != "" && city != "" && area == "") {
			if (level == "c") {
				for (const city_name in data) {
					global_taskIsFinished[city_name] = false;
					querySingleCityBoundary(province, city_name, rank_color[data[city_name]]);
				}
			} else if (level == "a") {
				for (const area_name in data) {
					global_taskIsFinished[area_name] = false;
					querySingleAreaBoundary(province, city, area_name, rank_color[data[area_name]]);
				}
			}
		} else if (province != "" && city != "" && area != "") {
			if (level == "a") {
				for (const area_name in data) {
					global_taskIsFinished[area_name] = false;
					querySingleAreaBoundary(province, city, area_name, rank_color[data[area_name]]);
				}
			}
		}
	};
	var querySingleProvinceBoundary = function (provinceName, color) {
		clearPolygons();
		var formData = {province: provinceName};
		$.ajax({
			url: getBoundaryController() + "/getSingleProvinceBoundary",
			type: "POST",
			data: formData,
			success: function (data) {
				loading.close();
				//console.log(data);
				var coords = data[provinceName], geometries = coords.split("|");
				for (let i = 0; i < geometries.length; i++) {
					var geometry = geometries[i], subGeometries = geometry.split("#"), subGeometry_points = [];
					for (var j = 0; j < subGeometries.length; j++) {
						var lonlats = subGeometries[j].split(";"), lonlat, lon = 0, lat = 0, points = [];
						for (var k = 0;k < lonlats.length;k++) {
							lonlat = lonlats[k].split(",");
							lon = parseFloat(lonlat[0]); lat = parseFloat(lonlat[1]);
							points.push(new T.LngLat(lon, lat));
							global_points.push(new T.LngLat(lon, lat));
						}
						subGeometry_points.push(points);
					}
					var provincePolygon = new T.Polygon(subGeometry_points, {
						color: "#0000ff",
						weight: 1,
						opacity: 0.5,
						fillColor: color,
						fillOpacity: 0.7,
						district: provinceName
					});
					tdMap.addOverLay(provincePolygon);
					provincePolygon.addEventListener("click", function (obj) {
						console.log(obj);
						var target = obj.target, lnglat = obj.lnglat, district = target.options.district;
						console.log(target.getFillColor());
						global_infoWin.setContent(district + ": " + _rank_color[target.getFillColor()]);
						tdMap.openInfoWindow(global_infoWin, lnglat);
					});
					global_polygons.push(provincePolygon);
				}
				global_taskIsFinished[provinceName] = true;
				console.log(global_taskIsFinished);
				taskIsFinish(global_taskIsFinished) && (tdMap.setViewport(global_points), global_points = [], global_taskIsFinished = {});
			}
		});
	};
	var querySingleCityBoundary = function (provinceName, cityName, color) {
		clearPolygons();
		var formData = {province: provinceName, city: cityName};
		$.ajax({
			url: getBoundaryController() + "/getSingleCityBoundary",
			type: "POST",
			data: formData,
			success: function (data) {
				loading.close();
				//console.log(data);
				if (!data) return;
				var coords = data[cityName], geometries = coords.split("|");
				for (let i = 0; i < geometries.length; i++) {
					var geometry = geometries[i], subGeometries = geometry.split("#"), subGeometry_points = [];
					for (var j = 0; j < subGeometries.length; j++) {
						var lonlats = subGeometries[j].split(";"), lonlat, lon = 0, lat = 0, points = [];
						for (var k = 0;k < lonlats.length;k++) {
							lonlat = lonlats[k].split(",");
							lon = parseFloat(lonlat[0]); lat = parseFloat(lonlat[1]);
							points.push(new T.LngLat(lon, lat));
							global_points.push(new T.LngLat(lon, lat));
						}
						subGeometry_points.push(points);
					}
					var cityPolygon = new T.Polygon(subGeometry_points, {
						color: "#0000ff",
						weight: 1,
						opacity: 0.5,
						fillColor: color,
						fillOpacity: 0.7,
						district: provinceName + ", " + cityName
					});
					tdMap.addOverLay(cityPolygon);
					cityPolygon.addEventListener("click", function (obj) {
						console.log(obj);
						var target = obj.target, lnglat = obj.lnglat, district = target.options.district;
						console.log(target.getFillColor());
						global_infoWin.setContent(district + ": " + _rank_color[target.getFillColor()]);
						tdMap.openInfoWindow(global_infoWin, lnglat);
					});
					global_polygons.push(cityPolygon);
				}
				global_taskIsFinished[cityName] = true;
				console.log(global_taskIsFinished);
				taskIsFinish(global_taskIsFinished) && (tdMap.setViewport(global_points), global_points = [], global_taskIsFinished = {});
			}
		});
	};
	var querySingleAreaBoundary = function (provinceName, cityName, areaName, color) {
		clearPolygons();
		var formData = {province: provinceName, city: cityName, area: areaName};
		$.ajax({
			url: getBoundaryController() + "/getSingleAreaBoundary",
			type: "POST",
			data: formData,
			success: function (data) {
				loading.close();
				//console.log(data);
				var coords = data[areaName], geometries = coords.split("|");
				for (let i = 0; i < geometries.length; i++) {
					var geometry = geometries[i], subGeometries = geometry.split("#"), subGeometry_points = [];
					for (var j = 0; j < subGeometries.length; j++) {
						var lonlats = subGeometries[j].split(";"), lonlat, lon = 0, lat = 0, points = [];
						for (var k = 0;k < lonlats.length;k++) {
							lonlat = lonlats[k].split(",");
							lon = parseFloat(lonlat[0]); lat = parseFloat(lonlat[1]);
							points.push(new T.LngLat(lon, lat));
							global_points.push(new T.LngLat(lon, lat));
						}
						subGeometry_points.push(points);
					}
					var areaPolygon = new T.Polygon(subGeometry_points, {
						color: "#0000ff",
						weight: 1,
						opacity: 0.5,
						fillColor: color,
						fillOpacity: 0.7,
						district: provinceName + ", " + cityName + ", " + areaName
					});
					tdMap.addOverLay(areaPolygon);
					areaPolygon.addEventListener("click", function (obj) {
						console.log(obj);
						var target = obj.target, lnglat = obj.lnglat, district = target.options.district;
						console.log(target.getFillColor());
						global_infoWin.setContent(district + ": " + _rank_color[target.getFillColor()]);
						tdMap.openInfoWindow(global_infoWin, lnglat);
					});
					global_polygons.push(areaPolygon);
				}
				global_taskIsFinished[areaName] = true;
				console.log(global_taskIsFinished);
				taskIsFinish(global_taskIsFinished) && (tdMap.setViewport(global_points), global_points = [], global_taskIsFinished = {});
			}
		});
	};
	var queryCitiesBoundaryByProvince = function (provinceName) {
		clearPolygons();
		$.ajax({
			url: getBoundaryController() + "/getCitiesBoundaryByProvince?provinceName=" + provinceName,
			type: "get",
			success: function (city2boundary) {
				console.log(city2boundary);
				var _points = [];
				for (const cityName in city2boundary) {
					var coords = city2boundary[cityName], coords = coords.split("|");
					for (let j = 0; j < coords.length; j++) {
						var lonlats = coords[j].split(";"), lonlat, lon = 0, lat = 0, points = [];
						for (var i = 0;i < lonlats.length;i++) {
							lonlat = lonlats[i].split(",");
							lon = parseFloat(lonlat[0]); lat = parseFloat(lonlat[1]);
							points.push(new T.LngLat(lon, lat));
						}
						_points = _points.concat(points);
						var min_value = 0, max_value = 1;
						changeColorLabel(min_value, max_value);
						var color = getPolygonColorByValue(Math.random(), min_value, max_value);
						var areaPolygon = new T.Polygon(points, {
							color: "#0000ff",
							weight: 1,
							opacity: 0.5,
							fillColor: color,
							fillOpacity: 0.5
						});
						tdMap.addOverLay(areaPolygon);
						global_polygons.push(areaPolygon);
					}
				}
				tdMap.setViewport(_points);
			}
		});
	};
	var queryAreasBoundaryByProvinceAndCity = function (provinceName, cityName) {
		clearPolygons();
		(cityName == "北京市") && (cityName = "北京城区");
		(cityName == "天津市") && (cityName = "天津城区");
		$.ajax({
			url: getBoundaryController() + "/getAreasBoundaryByProvinceAndCity?provinceName=" + provinceName + "&cityName=" + cityName,
			type: "get",
			success: function (data) {
				console.log(data);
				var areas = data[cityName], _points = [];
				for (const areaName in areas) {
					var coords = areas[areaName], coords = coords.split("|");
					for (let j = 0; j < coords.length; j++) {
						var lonlats = coords[j].split(";"), lonlat, lon = 0, lat = 0, points = [];
						for (var i = 0;i < lonlats.length;i++) {
							lonlat = lonlats[i].split(",");
							lon = parseFloat(lonlat[0]); lat = parseFloat(lonlat[1]);
							points.push(new T.LngLat(lon, lat));
						}
						_points = _points.concat(points);
						var min_value = 0, max_value = 1;
						changeColorLabel(min_value, max_value);
						var color = getPolygonColorByValue(Math.random(), min_value, max_value);
						var areaPolygon = new T.Polygon(points, {
							color: "#0000ff",
							weight: 1,
							opacity: 0.5,
							fillColor: color,
							fillOpacity: 0.5
						});
						//console.log(areaPolygon);
						tdMap.addOverLay(areaPolygon);
						global_polygons.push(areaPolygon);
					}
				}
				tdMap.setViewport(_points);
			}
		});
	};
	var queryProvincesByCoords = function (coords_str, coords) {
		loading.show();
		$.ajax({
			url: getBoundaryController() + "/isPolygonsIntersect?coords=" + coords_str,
			type: "GET",
			success: function (data) {
				console.log(data);
				for (let i = 0; i < data.length; i++) {
					queryDistrictData(coords, data[i]);
				}
			}
		});
	};
	var swapObj = function (obj) {
		var res = {}, tmp, tmp_key;
		for (var obj_key in obj) {
			if (obj_key.indexOf(",") == -1) return obj;
			tmp = obj_key.split(",");
			tmp_key = tmp[1];
			res[tmp_key] = obj[obj_key];
		}
		return [tmp[0], res];
	};
	var taskIsFinish = function (obj) {
		for (var _key in obj) if (!obj[_key]) return false;
		return true;
	}

	var global_polygons = [], polygonTool;
	//var rank_color = {"轻微": "#00FF00", "一般": "#F6C568", "重点": "#FF0000"}, _rank_color = {"#00FF00": "轻微", "#F6C568": "一般", "#FF0000": "重点"};
	//var rank_color = {"轻微": "#FCDAD5", "一般": "#EE7C6B", "重点": "#B2001F"}, _rank_color = {"#FCDAD5": "轻微", "#EE7C6B": "一般", "#B2001F": "重点"};
	var rank_color = {"轻微": "#D9BFD9", "一般": "#993399", "重点": "#5D164E"}, _rank_color = {"#D9BFD9": "轻微", "#993399": "一般", "#5D164E": "重点"};
	_rank_color = {"#D9BFD9": "低风险", "#993399": "中风险", "#5D164E": "高风险"}
	var global_points = [], global_taskIsFinished = {};
	var global_infoWin = new T.InfoWindow(""), loading = Loading({text : "正在查询数据..."});
	var initMap = function() {
		var mapH = document.body.clientHeight - $(".pd-search-container").height() - 10;
		$("#yhHiddenLevelMap").height(mapH);

		var vec_layer = new T.TileLayer("https://fxpc.mem.gov.cn/data_preparation/171dd1d5-bbb3-483a-a7f6-50d6d98cee1f/d9ffc071-50dd-4780-a617-673d17921e22/wmts?service=wmts&request=gettile&version=1.0.0&layer=vec&style=default&tilematrixset=c&format=tiles&tilematrix={z}&tilerow={y}&tilecol={x}&geokey=94E99EB4FEB9B48CD5348F7BCF5BB620");
		var cva_layer = new T.TileLayer("https://fxpc.mem.gov.cn/data_preparation/171dd1d5-bbb3-483a-a7f6-50d6d98cee1f/13f8b69d-98dc-4276-bbf0-9c4c372acabc/wmts?service=wmts&request=gettile&version=1.0.0&layer=cva&style=default&tilematrixset=c&format=tiles&tilematrix={z}&tilerow={y}&tilecol={x}&geokey=94E99EB4FEB9B48CD5348F7BCF5BB620");
		var config = {
			projection: 'EPSG:4326',
			minZoom: 4,
			layers: [vec_layer, cva_layer]
		};
		tdMap = new T.Map('yhHiddenLevelMap', config), zoom = 4;
		tdMap.centerAndZoom(new T.LngLat(106.34766, 34.37971), zoom);

		var control=new T.Control.Zoom();
		tdMap.addControl(control);

		//创建比例尺控件对象
		var scale = new T.Control.Scale();
		tdMap.addControl(scale);

		var config = {showLabel: false, color: "blue", weight: 3, opacity: 0.5, fillColor: "#FFFFFF", fillOpacity: 0.5
		};
		//创建标注工具对象
		polygonTool = new T.PolygonTool(tdMap, config);
	};
	var clearPolygons = function () {
		tdMap.closeInfoWindow();
		for (let i = 0; i < global_polygons.length; i++) {
			tdMap.removeOverLay(global_polygons[i]);
		}
		global_polygons = [];
	};

	return {
		init:init
	};
});
